<!--
  智慧小区管理系统 - 数据权限过滤组件
  @author Wu.Liang
  @date 2024-01-01
  @updated 2024-12-21 - 完善数据权限过滤组件功能
-->
<template>
  <div class="data-scope-filter">
    <el-form :model="filterForm" inline>
      <el-form-item label="数据范围">
        <el-select
          v-model="filterForm.dataScope"
          placeholder="请选择数据范围"
          clearable
          @change="handleDataScopeChange"
        >
          <el-option
            v-for="item in dataScopeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="showCustomSelect" label="自定义范围">
        <el-select
          v-model="filterForm.customScopes"
          multiple
          placeholder="请选择自定义范围"
          clearable
          @change="handleCustomScopeChange"
        >
          <el-option
            v-for="item in customScopeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useUserStore } from '@/store/user'
import { ROLE_CODES } from '@/constants/roles'
import { isSuperAdmin, getDataScopeText, getDataScopeDescription, getDataScopeTagType } from '@/utils/permission'

// Props
interface Props {
  dataField?: string
  showCustomSelect?: boolean
  customOptions?: Array<{ value: string; label: string }>
}

const props = withDefaults(defineProps<Props>(), {
  dataField: 'communityId',
  showCustomSelect: false,
  customOptions: () => []
})

// Emits
const emit = defineEmits<{
  'scope-change': [scopes: string[]]
  'filter-change': [filteredData: any[]]
}>()

// Store
const userStore = useUserStore()

// 响应式数据
const filterForm = ref({
  dataScope: 'all',
  customScopes: [] as string[]
})

// 计算属性
const dataScopeOptions = computed(() => {
  const options = [
    { value: 'all', label: '全部数据' },
    { value: 'self', label: '我的数据' },
    { value: 'custom', label: '自定义范围' }
  ]

      // 如果不是超级管理员，隐藏"全部数据"选项
    if (!isSuperAdmin()) {
      return options.filter(option => option.value !== 'all')
    }

  return options
})

const customScopeOptions = computed(() => {
  if (props.customOptions.length > 0) {
    return props.customOptions
  }

  // 默认从用户数据权限范围生成选项
  const userDataScope = userStore.userDataScope || []
  return userDataScope.map(scope => ({
    value: scope,
    label: `范围 ${scope}`
  }))
})

// 获取数据权限范围文本
const getDataScopeTextComputed = computed(() => {
  return getDataScopeText(userStore.userDataScope)
})

// 获取数据权限范围描述
const getDataScopeDescriptionComputed = computed(() => {
  return getDataScopeDescription(userStore.userDataScope)
})

// 获取数据权限范围标签类型
const getDataScopeTagTypeComputed = computed(() => {
  return getDataScopeTagType(userStore.userDataScope)
})

// 方法
const handleDataScopeChange = (value: string) => {
  let scopes: string[] = []

  switch (value) {
    case 'all':
      scopes = []
      break
    case 'self':
      scopes = userStore.userDataScope || []
      break
    case 'custom':
      scopes = filterForm.value.customScopes
      break
  }

  emit('scope-change', scopes)
}

const handleCustomScopeChange = (values: string[]) => {
  filterForm.value.customScopes = values
  if (filterForm.value.dataScope === 'custom') {
    emit('scope-change', values)
  }
}

// 数据过滤方法
const filterData = (data: any[]): any[] => {
  const scope = filterForm.value.dataScope
  const customScopes = filterForm.value.customScopes

      // 超级管理员可以查看所有数据
    if (isSuperAdmin()) {
      if (scope === 'all') {
        return data
      }
  }

  let targetScopes: string[] = []

  switch (scope) {
    case 'all':
      return data
    case 'self':
      targetScopes = userStore.userDataScope || []
      break
    case 'custom':
      targetScopes = customScopes
      break
  }

  if (targetScopes.length === 0) {
    return []
  }

  return data.filter(item => {
    const itemValue = item[props.dataField]
    return targetScopes.includes(itemValue?.toString())
  })
}

// 暴露方法给父组件
defineExpose({
  filterData,
  getCurrentScopes: () => {
    const scope = filterForm.value.dataScope
    switch (scope) {
      case 'all':
        return []
      case 'self':
        return userStore.userDataScope || []
      case 'custom':
        return filterForm.value.customScopes
      default:
        return []
    }
  },
  resetFilter: () => {
    filterForm.value.dataScope = 'all'
    filterForm.value.customScopes = []
  }
})

// 监听数据范围变化
watch(
  () => filterForm.value.dataScope,
  (newScope) => {
    handleDataScopeChange(newScope)
  }
)
</script>

<style scoped>
.data-scope-filter {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.data-scope-filter .el-form-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.data-scope-filter .el-select {
  width: 200px;
}
</style> 